package com.gitee.mars.tourserver.exception;

import com.gitee.mars.tourserver.response.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author wq
 * @version 1.0
 * @date 2020/12/15 18:38
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("{}", e);
        String message = e.getMessage();
        return R.error(message);
    }

    /**
     * 参数校验
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = BindException.class)
    public R<String> bindException(BindException e) {
        log.error("{}", e);
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        return R.error(allErrors.get(0).getDefaultMessage());
    }

    /**
     * 业务中的异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = WorkException.class)
    public R<String> workException(WorkException e) {
        log.error("{}", e);
        return R.error(e.getMessage());
    }

    /**
     * aop的异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = AopException.class)
    public R<String> aopException(AopException e) {
        log.error("{}", e);
        return R.error(e.getMessage());
    }

    /**
     * 总异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = Exception.class)
    public R<String> exception(Exception e) {
        log.error("{}", e);
        return R.error("网络异常,稍后重试");
    }
}
